<template>
  <div class="product-reviews-page">
    <Header />

    <div class="container">
      <!-- 商品信息头部 -->
      <div class="product-header" v-if="product">
        <div class="product-info">
          <img :src="product.productImg || require('@/assets/product-default.png')" 
               :alt="product.productName" class="product-image" />
          <div class="product-details">
            <h1 class="product-name">{{ product.productName }}</h1>
            <div class="product-meta">
              <span class="price">¥{{ formatPrice(product.sellingPrice) }}</span>
              <span class="sales">销量: {{ product.sales || 0 }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 评价统计 -->
      <div class="reviews-summary">
        <div class="summary-header">
          <h2>用户评价 ({{ reviews.length }})</h2>
          <div class="back-to-product">
            <el-button @click="backToProduct">返回商品详情</el-button>
          </div>
        </div>

        <div v-if="reviews.length > 0" class="rating-overview">
          <div class="average-rating">
            <div class="rating-score">{{ averageRating }}</div>
            <div class="rating-stars">
              <el-rate v-model="averageRating" disabled show-score :max="5" />
            </div>
            <div class="rating-text">综合评分</div>
          </div>
          
          <div class="rating-breakdown">
            <div v-for="i in 5" :key="i" class="rating-bar">
              <span class="star-count">{{ 6 - i }}星</span>
              <div class="bar-container">
                <div class="bar-fill" 
                     :style="{ width: getRatingPercentage(6 - i) + '%' }"></div>
              </div>
              <span class="count">{{ getRatingCount(6 - i) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 评价列表 -->
      <div class="reviews-content">
        <div v-if="loading" class="loading">
          <div class="spinner"></div>
          <span>加载中...</span>
        </div>

        <div v-else-if="error" class="error-message">
          <div class="error-icon">⚠️</div>
          <div class="error-text">{{ error }}</div>
          <button class="retry-btn" @click="fetchReviews">重试</button>
        </div>

        <div v-else-if="reviews.length === 0" class="empty-reviews">
          <div class="empty-icon">📝</div>
          <div class="empty-text">暂无评价</div>
          <div class="empty-desc">成为第一个评价该商品的用户吧</div>
          <el-button type="primary" @click="backToProduct">返回商品详情</el-button>
        </div>

        <div v-else class="reviews-list">
          <div v-for="review in reviews" :key="review.detailId" class="review-card">
            <div class="review-header">
              <div class="user-info">
                <img :src="review.avatar || require('@/assets/default_avatar.png')" 
                     :alt="review.username" class="user-avatar" />
                <div class="user-details">
                  <span class="username">{{ review.username || '匿名用户' }}</span>
                  <div class="review-meta">
                    <el-rate v-model="review.rating" disabled :max="5" />
                    <span class="review-date">{{ formatDate(review.createTime) }}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="review-content">
              <p class="review-text">{{ review.reviewDetail }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElButton, ElRate } from 'element-plus';
import Header from '@/components/Header.vue';
import request from '@/utils/request';

// 响应式数据
const product = ref(null);
const reviews = ref([]);
const loading = ref(false);
const error = ref(null);

// 路由相关
const route = useRoute();
const router = useRouter();
const productId = computed(() => route.params.id);

// 计算属性
const averageRating = computed(() => {
  if (reviews.value.length === 0) return 0;
  const total = reviews.value.reduce((sum, review) => sum + (review.rating || 0), 0);
  return (total / reviews.value.length).toFixed(1);
});

// 方法
const formatPrice = (price) => {
  const num = Number(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
};

const getRatingCount = (rating) => {
  return reviews.value.filter(review => review.rating === rating).length;
};

const getRatingPercentage = (rating) => {
  if (reviews.value.length === 0) return 0;
  const count = getRatingCount(rating);
  return (count / reviews.value.length) * 100;
};

const fetchProduct = async () => {
  try {
    const response = await request.get(`/products/${productId.value}`);
    product.value = response.data;
  } catch (error) {
    console.error('获取商品信息失败:', error);
  }
};

const fetchReviews = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const response = await request.get(`/order-detail/product/${productId.value}/reviews`);
    if (response.data.status === 200) {
      reviews.value = response.data.data || [];
    }
  } catch (err) {
    console.error('获取商品评价失败:', err);
    error.value = '获取商品评价失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const backToProduct = () => {
  router.push(`/product/${productId.value}`);
};

// 生命周期
onMounted(() => {
  fetchProduct();
  fetchReviews();
});
</script>

<style scoped>
.product-reviews-page {
  background: var(--gray-50);
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: var(--spacing-6);
}

.product-header {
  background: var(--white);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  margin-bottom: var(--spacing-6);
  overflow: hidden;
}

.product-info {
  display: flex;
  align-items: center;
  padding: var(--spacing-6);
  gap: var(--spacing-4);
}

.product-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: var(--radius-md);
  background: var(--gray-100);
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 var(--spacing-4) 0;
  font-size: var(--font-size-2xl);
  color: var(--gray-900);
  font-weight: var(--font-weight-bold);
}

.product-meta {
  display: flex;
  align-items: center;
  gap: var(--spacing-6);
}

.price {
  font-size: var(--font-size-xl);
  color: var(--primary-color);
  font-weight: var(--font-weight-bold);
}

.sales {
  color: var(--gray-600);
  font-size: var(--font-size-sm);
}

.reviews-summary {
  background: var(--white);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  margin-bottom: var(--spacing-6);
  overflow: hidden;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-6);
  border-bottom: 1px solid var(--gray-200);
}

.summary-header h2 {
  margin: 0;
  font-size: var(--font-size-2xl);
  color: var(--gray-900);
}

.rating-overview {
  display: flex;
  padding: var(--spacing-6);
  gap: var(--spacing-8);
}

.average-rating {
  text-align: center;
  min-width: 200px;
}

.rating-score {
  font-size: 3rem;
  font-weight: var(--font-weight-bold);
  color: var(--primary-color);
  margin-bottom: var(--spacing-2);
}

.rating-stars {
  margin-bottom: var(--spacing-2);
}

.rating-text {
  color: var(--gray-600);
  font-size: var(--font-size-sm);
}

.rating-breakdown {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-3);
}

.rating-bar {
  display: flex;
  align-items: center;
  gap: var(--spacing-3);
}

.star-count {
  width: 40px;
  font-size: var(--font-size-sm);
  color: var(--gray-600);
}

.bar-container {
  flex: 1;
  height: 8px;
  background: var(--gray-200);
  border-radius: 4px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  background: var(--primary-color);
  transition: width 0.3s ease;
}

.count {
  width: 30px;
  text-align: right;
  font-size: var(--font-size-sm);
  color: var(--gray-600);
}

.reviews-content {
  background: var(--white);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  overflow: hidden;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-12);
  color: var(--gray-600);
}

.spinner {
  border: 3px solid var(--gray-200);
  border-top: 3px solid var(--primary-color);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-right: var(--spacing-3);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  padding: var(--spacing-8);
  text-align: center;
  background-color: #fff1f0;
  border-radius: var(--radius-lg);
  margin: var(--spacing-4);
}

.error-icon {
  font-size: 2rem;
  margin-bottom: var(--spacing-4);
}

.error-text {
  color: var(--error-color);
  margin-bottom: var(--spacing-4);
}

.retry-btn {
  padding: var(--spacing-2) var(--spacing-6);
  background-color: var(--error-color);
  color: var(--white);
  border: none;
  border-radius: var(--radius-md);
  cursor: pointer;
}

.empty-reviews {
  padding: var(--spacing-12);
  text-align: center;
  color: var(--gray-600);
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: var(--spacing-4);
}

.empty-text {
  font-size: var(--font-size-lg);
  margin-bottom: var(--spacing-2);
  color: var(--gray-800);
}

.empty-desc {
  color: var(--gray-500);
  margin-bottom: var(--spacing-6);
}

.reviews-list {
  padding: var(--spacing-6);
}

.review-card {
  border: 1px solid var(--gray-200);
  border-radius: var(--radius-lg);
  padding: var(--spacing-6);
  margin-bottom: var(--spacing-4);
  background: var(--white);
  transition: box-shadow var(--transition-fast);
}

.review-card:hover {
  box-shadow: var(--shadow-md);
}

.review-header {
  margin-bottom: var(--spacing-4);
}

.user-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-4);
}

.user-avatar {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 50%;
  background: var(--gray-100);
}

.user-details {
  flex: 1;
}

.username {
  font-weight: var(--font-weight-medium);
  color: var(--gray-900);
  margin-bottom: var(--spacing-2);
  display: block;
  font-size: var(--font-size-base);
}

.review-meta {
  display: flex;
  align-items: center;
  gap: var(--spacing-3);
}

.review-date {
  color: var(--gray-500);
  font-size: var(--font-size-sm);
}

.review-content {
  margin-top: var(--spacing-4);
}

.review-text {
  margin: 0;
  line-height: var(--line-height-relaxed);
  color: var(--gray-700);
  font-size: var(--font-size-base);
}

@media (max-width: 768px) {
  .container {
    padding: var(--spacing-4);
  }

  .product-info {
    flex-direction: column;
    text-align: center;
    padding: var(--spacing-4);
  }

  .product-image {
    width: 100px;
    height: 100px;
  }

  .product-meta {
    justify-content: center;
  }

  .summary-header {
    flex-direction: column;
    gap: var(--spacing-4);
    text-align: center;
  }

  .rating-overview {
    flex-direction: column;
    text-align: center;
  }

  .rating-breakdown {
    margin-top: var(--spacing-4);
  }

  .review-card {
    padding: var(--spacing-4);
  }

  .user-info {
    gap: var(--spacing-3);
  }

  .user-avatar {
    width: 40px;
    height: 40px;
  }
}
</style>
